package es.manuel.maa.applet.util;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;

public final class ReflectionUtils {

	private ReflectionUtils() {

	}

	@SuppressWarnings("unchecked")
	public static <E> E getInstance(String className) {
		return getInstance((Class<E>) getClass(className));
	}

	public static <E> E getInstance(final Class<E> clazz) {
		try {
			return AccessController
					.doPrivileged(new PrivilegedExceptionAction<E>() {
						public E run() throws Exception {
							return clazz.newInstance();
						}
					});
		} catch (PrivilegedActionException e) {
			throw new RuntimeException(e.getException());
		}
	}

	@SuppressWarnings("rawtypes")
	public static Class getClass(final String className) {
		try {
			return AccessController
					.doPrivileged(new PrivilegedExceptionAction<Class>() {
						public Class run() throws Exception {
							return Class.forName(className);

						}
					});
		} catch (PrivilegedActionException e) {
			throw new RuntimeException(e.getException());
		}
	}

	public static void setFieldValue(final Field field, final Object object,
			final Object value) {
		try {
			AccessController
					.doPrivileged(new PrivilegedExceptionAction<Object>() {
						public Object run() throws Exception {
							if (!field.isAccessible())
								field.setAccessible(true);
							field.set(object, value);
							return null;

						}
					});
		} catch (PrivilegedActionException e) {
			throw new RuntimeException(e.getException());
		}
	}

}
